import React, { PureComponent } from 'react';
// 引入样式
import './chat.scss';
// 引入框架
import { Input, Button, message } from 'antd';
// 发送axios
import Axios from 'axios';
// 引入接口
import { webSite } from '../../website';
// 引入store
import store from '../../store/index';
export default class Phone extends PureComponent {
  constructor() {
    super();
    this.state = {
      // 输入框
      input: '',
      // 用户名
      user: '默认用户',
    };
    // state的写法
    this.unSubscribe = store.subscribe(() => {
      // 强制更新
      this.forceUpdate();
    });
  }

  // 清除订阅者
  componentWillUnmount() {
    this.unSubscribe();
    // 卸载异步操作设置状态
    this.setState = () => {
      return;
    };
  }

  // 网页加载请求用户名
  componentDidMount() {
    let { userQq } = store.getState().reducer;
    if (userQq) {
      Axios.create({
        baseURL: `${webSite}:3003`,
      })
        .post('/getQqUser', { qqUser: userQq })
        .then((err) => {
          if (err.data.code === 'F0066') {
            this.setState({
              user: err.data.user,
            });
          }
        })
        .catch(() => {
          message.error({ content: '请检查您的网络连接', className: 'bulletChatMessage' });
        });
    }
  }

  // input的输入事件
  handleInput = ({ target }) => {
    let { name, value } = target;
    // 设置input和state同步
    this.setState({
      [name]: value,
    });
  };
  // 获取当前时间的函数
  getDate = () => {
    let now = new Date();
    let year = now.getFullYear(); //得到年份
    let month = now.getMonth() + 1; //得到月份
    let date = now.getDate(); //得到日期
    let day = now.getDay(); //得到周几
    let hour = now.getHours(); //得到小时
    let minu = now.getMinutes(); //得到分钟
    let sec = now.getSeconds(); //得到秒
    let arr_week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    let week = arr_week[day];
    return year + '-' + month + '-' + date + '   ' + week + '   ' + hour + ':' + minu + ':' + sec;
  };
  // 人的对话内容
  chatRen = (input) => {
    let { userQq } = store.getState().reducer;
    let qq = userQq
      ? `http://q1.qlogo.cn/g?b=qq&nk=${userQq}&s=640`
      : 'http://img2.imgtn.bdimg.com/it/u=3512203888,2478096728&fm=26&gp=0.jpg';

    let li = document.createElement('li');
    li.className = 'chat_chat_right';
    li.innerHTML = `
    <div class='chat_chat_img'>
      <img src=${qq} alt="qq头像" />
    </div>
    <div class='chat_chat_body'>
      <div class='chat_chat_span'>${this.state.user}</div>
      <div class='chat_chat_text'>${input}</div>
    </div>
  `;
    return li;
  };
  // 机器的返回内容
  chatJiqi = (input) => {
    let jqr = require('./img/1287973.gif');
    let li = document.createElement('li');
    li.className = 'chat_chat';
    li.innerHTML = `
    <div class='chat_chat_img'>
      <img src=${jqr} alt="机器人" />
    </div>
    <div class='chat_chat_body'>
      <div class='chat_chat_span_left'>机器人小柒</div>
      <div class='chat_chat_text'>${input}</div>
    </div>
  `;
    return li;
  };

  // 时间
  chatDate = () => {
    let li = document.createElement('li');
    li.className = 'chat_chat_date';
    li.innerHTML = this.getDate();
    return li;
  };

  ClickChat = () => {
    const _this = this;
    // 判断是否输入空格和未输入
    // 去掉空格
    let input = this.state.input.replace(/\s+/g, '');
    if (!input) {
      message.error({ content: '请输入内容', className: 'bulletChatMessage' });
      return;
    }
    // 把用户的话发送到页面上
    let UlNode = document.getElementById('chatUl');
    // 时间
    UlNode.appendChild(_this.chatDate());
    UlNode.appendChild(_this.chatRen(input));
    // 自动移动到最下面
    let ele = document.getElementById('chatUl');
    ele.scrollTop = ele.scrollHeight;

    //发送给后台
    Axios.create({
      baseURL: `${webSite}:3003`,
    })
      .post('/lifechat', { text: input })
      .then((err) => {
        if (err.data.code === 'F0010') {
          message.error({
            content: '当日可用对话次数已达上限，请明天在来',
            className: 'bulletChatMessage',
          });
        } else if (err.data.code === 'F0009') {
          // 把返回数据发送到页面上
          let UlNode = document.getElementById('chatUl');
          // 时间
          UlNode.appendChild(_this.chatDate());
          UlNode.appendChild(_this.chatJiqi(err.data.data.text));
          // 自动移动到最下面
          let ele = document.getElementById('chatUl');
          ele.scrollTop = ele.scrollHeight;
        }
      })
      .catch(() => {
        message.error({ content: '请检查您的网络连接', className: 'bulletChatMessage' });
      });
    // 清空输入框
    this.setState({
      input: '',
    });
  };
  render() {
    let jqr = require('./img/1287973.gif');
    return (
      <div className="chat">
        <div className="chat_top">性感AI，在线犯傻</div>
        {/* 聊天内容 */}
        <ul className="chat_body_ul" id="chatUl">
          {/* 机器人的内容 */}
          <li className="chat_chat">
            <div className="chat_chat_img">
              <img src={jqr} alt="机器人" />
            </div>
            <div className="chat_chat_body">
              <div className="chat_chat_span_left">机器人小柒</div>
              <div className="chat_chat_text">您好，我是小柒</div>
            </div>
          </li>
        </ul>
        {/* 发送消息的按钮 */}
        <div className="chat_bottom">
          <Input
            placeholder="输入聊天内容"
            className="chat_input"
            value={this.state.input}
            name="input"
            onChange={this.handleInput}
            autoComplete="off"
            maxLength="20"
            onPressEnter={this.ClickChat}
          />
          <Button type="primary" className="chat_button" onClick={this.ClickChat}>
            发送
          </Button>
        </div>
      </div>
    );
  }
}
